package kwic.pf;

import java.io.CharArrayWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ShiftFilter extends Filter {
	private List<String> noises = new ArrayList<String>();

	public ShiftFilter(String noiseFile, Pipe input, Pipe output) {
		super(input, output);
		try {
			Scanner in = new Scanner(new FileInputStream(noiseFile));
			while (in.hasNext()) {
				String word = in.nextLine();
				noises.add(word);
			}
			in.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			e.printStackTrace();
			System.err.println("KWIC Error: Could not read noises.");
		}
	}

	@Override
	protected void transform() {
		CharArrayWriter writer = new CharArrayWriter();
		boolean isValid = true;
		try {
			int c = input_.read();

			while (c != -1) {
				if (((char) c) == '\n') {
					String line = writer.toString();

					for (String noise : noises) {
						if (line.startsWith(noise)) {
							isValid = false;
							break;
						}
					}
					if (isValid) {
						line += '\n';
						char[] chars = line.toCharArray();
						for (char ch : chars) {
							output_.write(ch);
						}
					}
					isValid = true;
					writer.reset();
				} else {
					writer.write(c);
				}
				c = input_.read();
			}
			output_.closeWriter();
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("KWIC Error: Could filter noises.");
			System.exit(1);
		}
	}

}
